import { useState, useEffect, useRef } from 'react'
import axios from 'axios'
import Image from 'next/image'


// const fetchData = async () => {
//   const response = await fetch('/api/zytq?name=厦门&n=1&apiKey=eb92c63e8b560cdc6972a96fe4d6bb32')
//   const newData = await response.text()
//   setData(newData)
//   console.log('data:', data)
// }

export default function Weather () {
  const [weather, setWeather] = useState([])
  const [position, setPosition] = useState('')
  const [city, setCity] = useState('厦门')
  const inputValue = useRef()

  function enterSearchWeather (event) {
    if (event.key === 'Enter') {
      setCity(inputValue.current.value)
      inputValue.current.value = ''
    }

  }

  function searchWeather () {
    setCity(inputValue.current.value)
    inputValue.current.value = ''
  }

  useEffect(() => {

    // fetchData()
    axios({
      url: '/api/zytq',
      method: 'GET',
      params: {
        name: city,
        n: '1',
        apiKey: '52f3846c6912a8fb8476fde5ffede39b'
      }
    }).then((res) => {
      const data = res.data.split("\r\n")
      setPosition(data[0])
      const data1 = data.slice(2, 9)
      var weatherObj = {}

      // 遍历数组，将每个键值对添加到对象中
      data1.forEach(function (item) {
        // 将每个键值对按冒号分割成键和值
        var keyValue = item.split('：')
        var key = keyValue[0].trim() // 去除键的前后空格
        var value = keyValue[1].trim() // 去除值的前后空格

        // 将键值对添加到对象中
        weatherObj[key] = value
      })
      setWeather(weatherObj)
    })
  }, [city])

  return (
    <>
      <header className="relative bg-white shadow-md p-3">
        <h1>THIS IS WEATHER OF {position}</h1>
        <div className='absolute z-0 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'><input onKeyDown={enterSearchWeather} ref={inputValue} placeholder='城市' className=' p-1 ml-2 mr-2 border-2 rounded-lg outline-0 border-sky-500' type='search'></input>
          <button onClick={searchWeather} className='text-sky-500'>搜索</button></div>
      </header>
      <ul className='grid grid-cols-4 gap-6 max-w-4xl mt-4 ml-4'>
        {Object.keys(weather).map((key) => (
          <li key={key} className='basic-10 grid grid-cols-2 bg-white rounded-lg shadow-md pt-3 pb-3'>
            <div className='flex basis-20 flex-col justify-items-center items-center'>
              <div className='flex justify-items-center items-center'><Image src={`/svgs/${key}.svg`} alt="weatherLogo" width={40} height={40} /></div>
              <div className='text-xs'>{key}</div>
            </div>

            <div className='flex  items-center text-lg text-sky-500'>{weather[key]}</div>
          </li>
        ))}
      </ul>

    </>
  )
}